﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using SmartSpace.Web;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SmartSpace.WebApp._console.page
{
    public partial class page_navigation_list : System.Web.UI.Page
    {
        private Guid _pageId;
        private Guid _selectedId;

        protected void Page_Load(object sender, EventArgs e)
        {
            _pageId = new Guid(Request.QueryString["id"]);
            _selectedId = Request.GetGuid("selid");

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                ListResult<Navigation> menus = service.GetNavigations(SsSite.Application.Id, _pageId);

                if (menus.IsSuccess)
                {
                    _ctlTreeMenu.Nodes.Clear();
                    foreach (var item in menus.Data)
                    {
                        TreeNode node = new TreeNode();
                        node.Text = item.Caption;
                        node.NavigateUrl = string.Format("./page-navigation-list.aspx?id={0}&selid={1}", _pageId, item.Id);

                        if (item.Id == _selectedId)
                        {
                            node.Selected = true;
                        }

                        LoadMenuItems(node, item);
                        _ctlTreeMenu.Nodes.Add(node);
                    }
                }
            }

            _ctlLinkBack.NavigateUrl = string.Format("./page-list.aspx?id={0}", _pageId);
            if (_selectedId != Guid.Empty)
            {
                _ctlLinkCreate.NavigateUrl = string.Format("./page-navigation-add.aspx?id={0}&selid={1}", _pageId, _selectedId);
            }
            else
            {
                _ctlLinkCreate.NavigateUrl = string.Format("./page-navigation-add.aspx?id={0}", _pageId);
            }
        }

        private void LoadMenuItems(TreeNode parentNode, Navigation parentelement)
        {
            foreach (var item in parentelement.Children)
            {
                TreeNode node = new TreeNode();
                node.Text = item.Caption;

                if (item.Id == _selectedId)
                {
                    node.Selected = true;
                }

                node.NavigateUrl = string.Format("./page-navigation-list.aspx?id={0}&selid={1}", _pageId, item.Id);
                parentNode.ChildNodes.Add(node);
            }
        }
    }
}